package com.education.cloud.gateway.fallback;

import com.alibaba.fastjson.JSON;
import com.education.cloud.util.base.Result;
import com.education.cloud.util.enums.ResultEnum;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description 网关层服务熔断
 * @Date 2020/3/24
 * @Created by 67068
 */
@Component
public class ServiceFallbackProvider implements FallbackProvider {

    @Override
    public String getRoute() {
        //Zuul 目前只支持服务级别的熔断，*代表所有后端微服务
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(JSON.toJSONString(Result.error(String.format(ResultEnum.SYSTEM_BUSY.getDesc(), route))).getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
